package de.karlNet.sambamanager.ldapController.commands.attributeBuilder;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import de.karlNet.Enums.BinaryMaskEnumMapper;
import de.karlNet.login.Useraccountcontrol;
import de.karlNet.sambamanager.ldapModel.LdapUser;

@Component
public class UserAttributeBuilder {
	private BinaryMaskEnumMapper<Useraccountcontrol> binaryMaskEnumMapper = new BinaryMaskEnumMapper<Useraccountcontrol>(
			Useraccountcontrol.class);
	int UF_ACCOUNTDISABLE = 0x0002;
	int UF_PASSWD_NOTREQD = 0x0020;
	int UF_PASSWD_CANT_CHANGE = 0x0040;
	int UF_NORMAL_ACCOUNT = 0x0200;
	int UF_DONT_EXPIRE_PASSWD = 0x10000;
	int UF_PASSWORD_EXPIRED = 0x800000;

	public List<BasicAttribute> buildUserAttributeList(LdapUser ldapUser)
			throws UnsupportedEncodingException {
		ArrayList<BasicAttribute> attributes = new ArrayList<BasicAttribute>();
		if (StringUtils.isNotBlank(ldapUser.getUsername())) {
			BasicAttribute samaccountname = new BasicAttribute(
					"samaccountname", ldapUser.getUsername());
			attributes.add(samaccountname);
		}
		if (StringUtils.isNotBlank(ldapUser.getFirstname())) {
			BasicAttribute sn = new BasicAttribute("givenName",
					ldapUser.getFirstname());
			attributes.add(sn);
		}
		if (StringUtils.isNotBlank(ldapUser.getLastname())) {
			BasicAttribute lastname = new BasicAttribute("sn",
					ldapUser.getLastname());
			attributes.add(lastname);
		}

		if (StringUtils.isNotBlank(ldapUser.getPassword())) {
			final byte[] quotedPasswordBytes;
			final String quotedPassword = '"' + ldapUser.getPassword() + '"';
			quotedPasswordBytes = quotedPassword.getBytes("UTF-16LE");
			BasicAttribute password = new BasicAttribute("unicodePwd",
					quotedPasswordBytes);
			attributes.add(password);
		}
		BasicAttribute objectClass = new BasicAttribute("objectclass");
		objectClass.add("person");
		objectClass.add("inetOrgPerson");
		attributes.add(objectClass);

		int useraccountControlBits = this.binaryMaskEnumMapper.fromList(ldapUser.getUseraccountcontrols());
		
		BasicAttribute userAccountControl = new BasicAttribute(
				"userAccountControl");
		userAccountControl.add(Integer.toString(useraccountControlBits));
		attributes.add(userAccountControl);
		return attributes;
	}

	public BasicAttributes buildUserAttributes(LdapUser ldapUser)
			throws UnsupportedEncodingException {
		BasicAttributes basicAttributes = new BasicAttributes();
		for (BasicAttribute attribute : this.buildUserAttributeList(ldapUser)) {
			basicAttributes.put(attribute);
		}
		return basicAttributes;
	}

}
